package com.itlong.cloud.controller.project;

import com.alibaba.fastjson.JSON;
import com.itlong.cloud.POJO.DTO.operate.OperateDeviceManageGetPageDTO;
import com.itlong.cloud.POJO.PO.DeviceRunLogPO;
import com.itlong.cloud.POJO.PO.OperateUserInfoPO;
import com.itlong.cloud.POJO.PO.OperationSpecialLogPO;
import com.itlong.cloud.POJO.PO.TimeTaskAuthDeviceAddressInfoPO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateDeviceDetailsVO;
import com.itlong.cloud.POJO.VO.operate.OperatePassPercentVO;
import com.itlong.cloud.POJO.VO.operate.OperationOSSDownloadFileVo;
import com.itlong.cloud.POJO.VO.property.PropertyEquipAddressVO;
import com.itlong.cloud.POJO.VO.property.PropertyProjectUnitSimpleInfoVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.DataStatusEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.PropertyErrorCodeEnum;
import com.itlong.cloud.equip.commons.ICloudDeviceBaseServiceClient;
import com.itlong.cloud.equip.operate.IOperateDeviceManageServiceClient;
import com.itlong.cloud.equip.operate.IOperatePackageServiceClient;
import com.itlong.cloud.equip.property.IPropertyEquipServiceClient;
import com.itlong.cloud.project.property.IPropertyUnitInfoServiceClient;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.operate.IOperateUserInfoServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.random.IdWorker;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <desc>
 * 运营-设备管理控制器
 * </desc>
 *
 * @createDate 2019/01/17
 */
@RestController
@RequestMapping("/project/deviceManage")
public class OperateDeviceManageController extends BaseController {

    private final static Logger LOG = LoggerFactory.getLogger(OperateDeviceManageController.class);

    @Autowired
    private IOperateDeviceManageServiceClient iOperateDeviceManageServiceClient;

    @Autowired
    private IOperatePackageServiceClient iOperatePackageServiceClient;

    @Autowired
    IOperateUserInfoServiceClient userInfoServiceClient;

    @Autowired
    private ICloudDeviceBaseServiceClient iCloudDeviceBaseService;

    @Autowired
    IPropertyEquipServiceClient iPropertyEquipServiceClient;

    @Autowired
    IPropertyUnitInfoServiceClient iPropertyUnitInfoServiceClient;

    @Autowired
    RedisService redisService;

    @Value("${" + PlatformConstants.ALIBABA_OSS_REGION + "}")
    public String ALIBABA_OSS_REGION;
    @Value("${" + PlatformConstants.ALIBABA_OSS_ACCESSID + "}")
    public String ALIBABA_OSS_ACCESSID;
    @Value("${" + PlatformConstants.ALIBABA_OSS_ACCESSKEY + "}")
    public String ALIBABA_OSS_ACCESSKEY;
    @Value("${" + PlatformConstants.ALIBABA_OSS_BUCKET + "}")
    public String ALIBABA_OSS_BUCKET;
    @Value("${" + PlatformConstants.ALIBABA_OSS_DIR + "}")
    public String ALIBABA_OSS_DIR;
    @Value("${" + PlatformConstants.ALIBABA_OSS_MEDIA_DIR + "}")
    public String ALIBABA_OSS_MEDIA_DIR;
    @Value("${" + PlatformConstants.ALIBABA_OSS_CALLBACKURL + "}")
    public String ALIBABA_OSS_CALLBACKURL;

    final IdWorker idWorker = new IdWorker(18);

    /**
     * <desc>
     * 获取设备分页列表
     * </desc>
     *
     * @param dto 查询参数DTO
     * @return
     * @author Qiang.S
     * @createDate 2019/01/17
     */
    @RequestMapping(path = "/getDeviceByPage", method = RequestMethod.POST)
    @ResponseBody
    @AuthAccessRequired
    public Object getDeviceByPage(OperateDeviceManageGetPageDTO dto) {
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto = HttpProtocolUtil.parseRequestParamToDTO(OperateDeviceManageGetPageDTO.class, request);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iOperateDeviceManageServiceClient.getDeviceByPage(dto));
        } catch (Exception e) {
            throw new DataAccessException("【运营_项目管理_设备信息getPage】获取分页列表失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     * 获取每个设备所占比例及统计在线与离线设备
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate 2019/10/28
     */
    @RequestMapping(path = "/getOperateDeviceInfo", method = RequestMethod.POST)
    @ResponseBody
    public Object getOperateDeviceInfo() {
        MessageVO messageVO;
        try {
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iOperateDeviceManageServiceClient.getOperateDeviceInfo());
        } catch (Exception e) {
            throw new DataAccessException("【运营-项目管理-查询设备相关信息】获取每种设备所占百分比失败", e);
        }
        return messageVO;
    }

    //设备日志文件下载 （暂时弃用）
    /*@RequestMapping("/download_File")
    public void download_File(String runLogId) {
        OutputStream os = null;
        InputStream inputStream = null;
        OSS ossClient = null;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            runLogId = request.getAttribute("runLogId") + "";
            if (StringUtils.isBlank(runLogId)) {
                throw new DataAccessException("【运营_设备日志文件下载】 设备编号不可为空");
            }
            // 获取设备信息
            DeviceRunLogPO deviceRunLogInfo = iOperateDeviceManageServiceClient.getDeviceRunLogInfo(runLogId);
            if (deviceRunLogInfo == null || StringUtils.isBlank(deviceRunLogInfo.getFileName())) {
                throw new DataAccessException("【运营_设备日志文件下载】 设备信息或文件不存在");
            }
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            // Endpoint以杭州为例，其它Region请按实际情况填写。
            String endpoint = ALIBABA_OSS_ENDPOINT;
            // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
            String accessKeyId = ALIBABA_OSS_ACCESSID;
            String accessKeySecret = ALIBABA_OSS_ACCESSKEY;
            String bucketName = ALIBABA_OSS_BUCKET;
            //<yourObjectName>表示从OSS下载文件时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
            String objectName = deviceRunLogInfo.getFileName();

            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
            if (ossObject == null) {
                throw new DataAccessException("【运营_设备日志文件下载】 当前日志文件不存在");
            }
            inputStream = ossObject.getObjectContent();
            int n = 0;
            byte[] buf = new byte[4 * 1024];
            *//* 设置文件ContentType类型，这样设置，会自动判断下载文件类型 *//*
            response.setContentType("multipart/form-data");
            *//* 设置文件头：最后一个参数是设置下载文件名 *//*
            response.setHeader("Content-Disposition", "attachment;filename=" + objectName);
            os = response.getOutputStream();

            while ((n = inputStream.read(buf, 0, buf.length)) != -1) {
                os.write(buf, 0, n);
            }
            os.flush();
            os.close();
            inputStream.close();
        } catch (Exception e) {
            Log.error(e.getMessage());
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                if (ossClient != null) {
                    // 关闭OSSClient。
                    ossClient.shutdown();
                }

            } catch (IOException e) {
                Log.error(e.getMessage());
            }
        }
    }*/


    /**
     * <desc>
     * 设备日志文件下载
     * </desc>
     *
     * @param
     * @return
     * @author caoshuai
     * @createDate 2020/11/13 18:46
     */
    @RequestMapping("/downloadFile")
    public Object downloadFile(String runLogId,String deviceUnique, String operateFunction) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        runLogId = request.getAttribute("runLogId") + "";
        deviceUnique = request.getAttribute("deviceUnique") + "";
        operateFunction = request.getAttribute("operateFunction") + "";
        SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
        String ip = HttpProtocolUtil.getIpAddr(request);
        String myUserName = request.getAttribute("myUserName") == null ? null : request.getAttribute("myUserName").toString();
        String operateWay = request.getAttribute("operateWay") == null ? null : request.getAttribute("operateWay").toString();
        //获取登录用户信息
        OperateUserInfoPO operateUserInfoPO = iOperateDeviceManageServiceClient.getOperateUserPO(myUserName);
        String token = request.getAttribute("token")+ "";
        OperateUserInfoPO user = userInfoServiceClient.retrieve(token);
        OperationSpecialLogPO operationSpecialLog = new OperationSpecialLogPO();
        operationSpecialLog.setLogId(idWorker.nextId() + "");
        operationSpecialLog.setIp(ip);
        operationSpecialLog.setRealName(operateUserInfoPO.getRealName());
        operationSpecialLog.setOperateWay(operateWay);
        operationSpecialLog.setOuterId(deviceUnique);
        operationSpecialLog.setAccount(user.getUserName());
        operationSpecialLog.setOperateFunction(operateFunction);
        Date nowTime = new Date();
        operationSpecialLog.setCreateTime(nowTime);
        operationSpecialLog.setOperateDec(operationSpecialLog.getRealName() + "于" + dateFormat.format(nowTime) + "做设备日志下载操作，" + "runLogId：" + runLogId);
        Integer row = iOperateDeviceManageServiceClient.saveOperationSpecialLog(operationSpecialLog);

        if (StringUtils.isBlank(runLogId)) {
            throw new DataAccessException("【运营_设备日志文件下载】 设备编号不可为空");
        }
        // 获取设备运行日志信息
        DeviceRunLogPO deviceRunLogInfo = iOperateDeviceManageServiceClient.getDeviceRunLogInfo(runLogId);
        if (deviceRunLogInfo == null || StringUtils.isBlank(deviceRunLogInfo.getFileName())) {
            throw new DataAccessException("【运营_设备日志文件下载】 设备信息或文件不存在");
        }
        OperationOSSDownloadFileVo operationOSSDownloadFileVo = new OperationOSSDownloadFileVo();
        operationOSSDownloadFileVo.setRegion(ALIBABA_OSS_REGION);
        operationOSSDownloadFileVo.setAccessKeyId(ALIBABA_OSS_ACCESSID);
        operationOSSDownloadFileVo.setAccessKeySecret(ALIBABA_OSS_ACCESSKEY);
        operationOSSDownloadFileVo.setFileName(deviceRunLogInfo.getFileName());
        operationOSSDownloadFileVo.setBucketName(ALIBABA_OSS_BUCKET);
        operationOSSDownloadFileVo.setRegion(ALIBABA_OSS_REGION);
        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), operationOSSDownloadFileVo);
    }

    /**
     * <desc>
     * 删除运行日志
     * </desc>
     *
     * @param runLogId 运行日志逻辑ID
     * @return Object
     * @author caoshuai
     * @createDate 2020/11/16 13:40
     */
    @RequestMapping("/delRunLog")
    @ResponseBody
    public Object delRunLog(String runLogId,String deviceUnique, String operateFunction) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        runLogId = request.getAttribute("runLogId") + "";
        deviceUnique = request.getAttribute("deviceUnique") + "";
        operateFunction = request.getAttribute("operateFunction") + "";
        String token = request.getAttribute("token") + "";
        if (StringUtils.isBlank(runLogId)) {
            throw new DataAccessException("【运营_设备日志文件下载】 设备编号不可为空");
        }
        // 删除运行日志
        Integer row = iOperateDeviceManageServiceClient.delRunLog(runLogId);
        if (row <= 0) {
            return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(), row);
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
        String ip = HttpProtocolUtil.getIpAddr(request);
        String myUserName = request.getAttribute("myUserName") == null ? null : request.getAttribute("myUserName").toString();
        String operateWay = request.getAttribute("operateWay") == null ? null : request.getAttribute("operateWay").toString();
        //获取登录用户信息
        OperateUserInfoPO operateUserInfoPO = iOperateDeviceManageServiceClient.getOperateUserPO(myUserName);
        OperateUserInfoPO user = userInfoServiceClient.retrieve(token);
        OperationSpecialLogPO operationSpecialLog = new OperationSpecialLogPO();
        operationSpecialLog.setLogId(idWorker.nextId() + "");
        operationSpecialLog.setIp(ip);
        operationSpecialLog.setRealName(operateUserInfoPO.getRealName());
        operationSpecialLog.setOperateWay(operateWay);
        operationSpecialLog.setOuterId(deviceUnique);
        operationSpecialLog.setAccount(user.getUserName());
        operationSpecialLog.setOperateFunction(operateFunction);
        Date nowTime = new Date();
        operationSpecialLog.setCreateTime(nowTime);
        operationSpecialLog.setOperateDec(operationSpecialLog.getRealName() + "于" + dateFormat.format(nowTime) + "做设备日志删除操作，" + "runLogId：" + runLogId);
        row = iOperateDeviceManageServiceClient.saveOperationSpecialLog(operationSpecialLog);
        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), row);
    }


    /**
     * <desc>
     * 运行日志列表
     * </desc>
     *
     * @param deviceUnique 运行日志逻辑ID
     * @return Object
     * @author caoshuai
     * @createDate 2020/11/16 13:40
     */
    @RequestMapping("/getRunLogInfoPage")
    @ResponseBody
    public Object getRunLogInfoPage(String deviceUnique, Integer pageSize, Integer currentPage, String orderRule) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if(null == request.getAttribute("orderRule") || StringUtils.isBlank(request.getAttribute("orderRule") + "")){
            orderRule = "desc";
        }else {
            orderRule = request.getAttribute("orderRule") + "";
        }

        deviceUnique = request.getAttribute("deviceUnique") + "";

        pageSize = request.getAttribute("pageSize") == null ? 20 : Integer.valueOf(request.getAttribute("pageSize") + "");
        currentPage = request.getAttribute("currentPage") == null ? 1 : Integer.valueOf(request.getAttribute("currentPage") + "");
        Map<String, Object> runLogInfo = iOperateDeviceManageServiceClient.getRunLogInfoPage(deviceUnique, pageSize, currentPage, orderRule);
        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), runLogInfo);
    }

    /**
     * <desc>
     * 设备重启
     * </desc>
     *
     * @param
     * @return
     * @author caoshuai
     * @createDate 2020/11/25 9:23
     */
    @RequestMapping("/restartDevice")
    @ResponseBody
    public Object restartDevice(String deviceUnique, String operateFunction, String deviceType) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        deviceUnique = request.getAttribute("deviceUnique") + "";
        String token = request.getAttribute("token") + "";
        operateFunction = request.getAttribute("operateFunction") + "";
        deviceType = request.getAttribute("deviceType") + "";
        Integer row = iOperateDeviceManageServiceClient.restartDevice(deviceUnique, deviceType);
        SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
        String ip = HttpProtocolUtil.getIpAddr(request);
        String myUserName = request.getAttribute("myUserName") == null ? null : request.getAttribute("myUserName").toString();
        String operateWay = request.getAttribute("operateWay") == null ? null : request.getAttribute("operateWay").toString();
        //获取登录用户信息
        OperateUserInfoPO operateUserInfoPO = iOperateDeviceManageServiceClient.getOperateUserPO(myUserName);
        //获取登录用户信息
        OperateUserInfoPO user = userInfoServiceClient.retrieve(token);
        OperationSpecialLogPO operationSpecialLog = new OperationSpecialLogPO();
        operationSpecialLog.setLogId(idWorker.nextId() + "");
        operationSpecialLog.setIp(ip);
        operationSpecialLog.setRealName(operateUserInfoPO.getRealName());
        operationSpecialLog.setOperateWay(operateWay);
        operationSpecialLog.setOuterId(deviceUnique);
        operationSpecialLog.setAccount(user.getUserName());
        operationSpecialLog.setOperateFunction(operateFunction);
        Date nowTime = new Date();
        operationSpecialLog.setCreateTime(nowTime);
        operationSpecialLog.setOperateDec(operationSpecialLog.getRealName() + "于" + dateFormat.format(nowTime) + "做重启设备操作，" + "deviceUnique：" + deviceUnique);
        row = iOperateDeviceManageServiceClient.saveOperationSpecialLog(operationSpecialLog);
        return new MessageVO(BaseErrorCodeEnum.RESTART_SUCCESS.getErrorCode(), row);
    }

    /**
     * <desc>
     * 获取设备日志
     * </desc>
     *
     * @param
     * @return
     * @author caoshuai
     * @createDate 2020/11/25 9:23
     */
    @RequestMapping("/getDeviceLog")
    @ResponseBody
    public Object getDeviceLog(String deviceUnique, String deviceId, String deviceType,String operateFunction) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        deviceUnique = request.getAttribute("deviceUnique") + "";
        deviceId = request.getAttribute("deviceId") + "";
        deviceType = request.getAttribute("deviceType") + "";
        operateFunction = request.getAttribute("operateFunction") + "";
        String myUserName = request.getAttribute("myUserName") == null ? null : request.getAttribute("myUserName").toString();
        String operateWay = request.getAttribute("operateWay") == null ? null : request.getAttribute("operateWay").toString();
        SimpleDateFormat dateFormat = new SimpleDateFormat(DateUtil.DATE_FORMAT_TYPE1);
        String ip = HttpProtocolUtil.getIpAddr(request);

        Integer row = iOperateDeviceManageServiceClient.getDeviceLog(deviceUnique, deviceId, deviceType);



        Map<Object, Object> receiveStatus = new HashMap<>();
        receiveStatus.put("phase", 4);
        receiveStatus.put("createTime", new Date());
        receiveStatus.put("fileName", "设备文件压缩中...");
        receiveStatus.put("fileSize", 0);
        receiveStatus.put("uploadStatus", 0);
        redisService.set(deviceUnique, 420L, JSON.toJSONString(receiveStatus));

        //获取登录用户信息
        OperateUserInfoPO operateUserInfoPO = iOperateDeviceManageServiceClient.getOperateUserPO(myUserName);
        String token = request.getAttribute("token")+ "";
        OperateUserInfoPO user = userInfoServiceClient.retrieve(token);
        OperationSpecialLogPO operationSpecialLog = new OperationSpecialLogPO();
        operationSpecialLog.setLogId(idWorker.nextId() + "");
        operationSpecialLog.setIp(ip);
        operationSpecialLog.setRealName(operateUserInfoPO.getRealName());
        operationSpecialLog.setOperateWay(operateWay);
        operationSpecialLog.setOuterId(deviceUnique);
        operationSpecialLog.setAccount(user.getUserName());
        operationSpecialLog.setOperateFunction(operateFunction);
        Date nowTime = new Date();
        operationSpecialLog.setCreateTime(nowTime);
        operationSpecialLog.setOperateDec(operationSpecialLog.getRealName() + "于" + dateFormat.format(nowTime) + "做获取设备日志操作");
        iOperateDeviceManageServiceClient.saveOperationSpecialLog(operationSpecialLog);

        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), row);
    }

    /**
     * <desc>
     * 获取详情
     * </desc>
     *
     * @param
     * @return
     * @author caoshuai
     * @createDate 2020/11/25 9:23
     */
    @RequestMapping("/getDeviceDetails")
    @ResponseBody
    public Object getDeviceDetails(String deviceUnique) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        deviceUnique = request.getAttribute("deviceUnique") + "";
        OperateDeviceDetailsVO operateDeviceDetailsVO = iOperateDeviceManageServiceClient.getDeviceDetails(deviceUnique);
        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), operateDeviceDetailsVO);
    }

    /**
     * <desc>
     * 设备上下线日志
     * </desc>
     *
     * @param
     * @return
     * @author caoshuai
     * @createDate 2020/11/25 9:23
     */
    @RequestMapping("/getDeviceOnlineStatusAlterLogPage")
    @ResponseBody
    public Object getDeviceOnlineStatusAlterLogPage(String deviceUnique, Integer pageSize, Integer currentPage) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        deviceUnique = request.getAttribute("deviceUnique") + "";
        pageSize = request.getAttribute("pageSize") == null ? 20 : Integer.valueOf(request.getAttribute("pageSize") + "");
        currentPage = request.getAttribute("currentPage") == null ? 1 : Integer.valueOf(request.getAttribute("currentPage") + "");

        Page result = iOperateDeviceManageServiceClient.getDeviceOnlineStatusAlterLogPage(deviceUnique, pageSize, currentPage);
        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), result);
    }

    /**
     * <desc>
     * 业务日志列表
     * </desc>
     *
     * @param
     * @return
     * @author caoshuai
     * @createDate 2020/11/30 10:44
     */
    @RequestMapping("/getOperationSpecialLogList")
    @ResponseBody
        public Object getDeviceOnlineStatusAlterLogPage(String deviceUnique, String pageSize, String currentPage, String orderColumn, String orderRule) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        deviceUnique = request.getAttribute("deviceUnique") + "";
        pageSize = request.getAttribute("pageSize") == null ? "20" : request.getAttribute("pageSize") + "";
        currentPage = request.getAttribute("currentPage") == null ? "1" : request.getAttribute("currentPage") + "";
        orderColumn = request.getAttribute("orderColumn") == null ? null : request.getAttribute("orderColumn").toString();
        orderRule = request.getAttribute("orderRule") == null ? null : request.getAttribute("orderRule").toString();

        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iOperatePackageServiceClient.getOperationSpecialLogList(deviceUnique, pageSize, currentPage, orderColumn, orderRule));
    }

    /**
     * <desc>
     *      获取文件传输进度数据
     * </desc>
     *
     * @param
     * @return
     * @author caoshuai
     * @createDate 2020/11/30 10:44
     */
    @RequestMapping("/getPercent")
    @ResponseBody
    public Object getPercent (String deviceUnique, Integer pageSize, Integer currentPage) throws Exception {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        deviceUnique = request.getAttribute("deviceUnique") + "";
        Map<String, Object> statusMap = JSON.parseObject(redisService.get(deviceUnique), HashMap.class);

        if(null == redisService.get(deviceUnique) || "".equals(redisService.get(deviceUnique)) || "3".equals(statusMap.get("phase") + "")) {
            if(null == statusMap){
                statusMap = new HashMap<>();
            }
            statusMap.put("buttonStatus", true);
            redisService.del("deviceUnique");
        }else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            statusMap.put("buttonStatus", false);
            statusMap.put("createTime", simpleDateFormat.format(new Date(Long.valueOf(statusMap.get("createTime") + ""))));
        }
        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), statusMap);
    }

    /**
     * <desc>
     *      获取开门占比
     * </desc>
     *
     * @param deviceUnique 设备唯一码
     * @return
     * @Author Zhu.yj
     * @createDate  2020/12/23
     */
    @PostMapping("/getOpenPercent")
    public Object getOpenPercent( String deviceUnique, HttpServletRequest request){
        try{
            deviceUnique = request.getAttribute("deviceUnique") == null ? null : request.getAttribute("deviceUnique").toString();
            if (deviceUnique == null){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            List<OperatePassPercentVO> deviceOpenTypeVOS = iOperateDeviceManageServiceClient.getOpenPercent(deviceUnique);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), deviceOpenTypeVOS);
        }catch (Exception e){
            throw new DataAccessException("【运营_设备管理getOpenPercent】获取开门占比失败", e);
        }
    }

    /**
     * <desc>
     *      修改设备的状态 删除、恢复
     * </desc>
     *
     * @param dto 查询参数DTO
     * @return
     * @author Juguang.S
     * @createDate 2020/12/02
     */
    @RequestMapping(path = "/modifyDeviceStatus",method = RequestMethod.POST)
    @ResponseBody
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.OPERATE_MODIFY_DEVICE_STATUS_LOG_DESC)
    public Object modifyDeviceStatus(OperateDeviceManageGetPageDTO dto){
        MessageVO messageVO;
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto= HttpProtocolUtil.parseRequestParamToDTO(OperateDeviceManageGetPageDTO.class,request);

            String projectId = StringHandlerUtil.getProjectIdByDeviceUnique(dto.getDeviceUnique());
            String token = request.getAttribute("token")+ "";
            OperateUserInfoPO user = userInfoServiceClient.retrieve(token);
            String loginUserId = user.getUserId();
//            String loginUserId = "dsfdsfdsffs321565516";

            //如果本项目已添加有效的批次号后，则需校验设备总数与项目下批次号之和的数量
            List<String> str= iPropertyEquipServiceClient.getBatchNumber(projectId,"0");
            if(str != null && !str.isEmpty()&& dto.getStatus()==1){
                Integer deviceType = Integer.parseInt(dto.getDeviceUnique().substring(8,9));
                Integer deviceCountByProject = iPropertyEquipServiceClient.getDeviceCountByType(deviceType,projectId,"");
                Integer limitCountByProject = iPropertyEquipServiceClient.getDeviceCountByBatchNumber(projectId,deviceType+"","");
                deviceCountByProject = deviceCountByProject==null?0:deviceCountByProject;
                if(limitCountByProject==null || limitCountByProject<=deviceCountByProject){
                    return new MessageVO(PropertyErrorCodeEnum.EQUIP_COUNT_PROJECT_IS_ZERO_BY_MODIFY.getErrorCode());
                }
            }

            //状态发生变化，查询受影响的住户，最终找到受影响用户的地址
            Set<String> unitIdSet = new HashSet<>();
            Set<String> equipOldUnitIds = this.getEquipOldUnitId(dto.getDeviceUnique());
            if (!equipOldUnitIds.isEmpty()) {
                unitIdSet.addAll(equipOldUnitIds);
            }
            //地址发生变化，将变化的地址存储的到定时任务表中
            if (!unitIdSet.isEmpty()) {
                Date date = new Date();
                TimeTaskAuthDeviceAddressInfoPO deviceAddrPO = new TimeTaskAuthDeviceAddressInfoPO(projectId, loginUserId, String.join(",", unitIdSet), DataStatusEnum.NORMAL.getType(), date, date);
                deviceAddrPO.setDeviceUniques(dto.getDeviceUnique());
                dto.setTimeTaskAuthDeviceAddressInfoPO(deviceAddrPO);
            }else{
                Date date = new Date();
                TimeTaskAuthDeviceAddressInfoPO deviceAddrPO = new TimeTaskAuthDeviceAddressInfoPO(projectId, loginUserId, "", DataStatusEnum.NORMAL.getType(), date, date);
                deviceAddrPO.setDeviceUniques(dto.getDeviceUnique());
                dto.setTimeTaskAuthDeviceAddressInfoPO(deviceAddrPO);
            }

            iOperateDeviceManageServiceClient.modifyDeviceStatus(dto);
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营_项目管理_设备信息modifyDeviceStatus】修改设备的状态 删除、恢复失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     * 根据设备唯一码查询设备归属地址，并精确到unitId
     * <desc/>
     *
     * @param deviceUnique 待查询的设备唯一码
     * @return 归属地精确到小区后的unitId集合
     * @author Biao.R
     * @createDate 2017/12/15
     */
    private Set<String> getEquipOldUnitId(String deviceUnique) {
        List<PropertyEquipAddressVO> oldEquipAddress = iPropertyEquipServiceClient.getEquipAddress(deviceUnique);
        Set<String> oldUnitIdSet = new HashSet<>();
        if (oldEquipAddress != null && !oldEquipAddress.isEmpty()) {
            List<String> oldBuildIdList = new ArrayList<>();
            for (PropertyEquipAddressVO oldAdress : oldEquipAddress) {
                List<PropertyProjectUnitSimpleInfoVO> units = oldAdress.getUnits();
                if (units != null && !units.isEmpty()) {
                    for (PropertyProjectUnitSimpleInfoVO unit : units) {
                        oldUnitIdSet.add(unit.getUnitId());
                    }
                } else {
                    oldBuildIdList.add(oldAdress.getBuildId());
                }
            }
            if (!oldBuildIdList.isEmpty()) {
                List<String> unitIdList = iPropertyUnitInfoServiceClient.getUnitIdInBuildIds(String.join(",", oldBuildIdList));
                oldUnitIdSet.addAll(unitIdList);
            }
        }
        return oldUnitIdSet;
    }
    /**
     * <desc>
     *      同步设备日志
     * </desc>
     *
     * @return
     * @Author maju
     * @createDate  2021/04/28
     */
    @PostMapping("/getDeviceLogByTask")
    public Object getOpenPercent(){
        try{
            iOperateDeviceManageServiceClient.getDeviceLogByTask();
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【同步设备日志】同步设备日志失败", e);
        }
    }

    /**
     * <desc>
     *      下载设备日志
     * </desc>
     *
     * @return
     * @Author maju
     * @createDate  2021/04/28
     */
    @PostMapping("/downloadDeviceLogByTask")
    public Object downloadDeviceLogByTask(){
        try{
            iOperateDeviceManageServiceClient.downloadDeviceLogByTask();
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【下载设备日志】下载设备日志失败", e);
        }
    }
}
